package app.widget;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.database.DataSetObserver;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import app.adapter.TableAdapter;
import app.log.APPLog;
import app.widget.PullListView.OnRefreshListener;

import com.longevityassistant.activity.R;

/**
 * 自定义TableView，固定表头
 * 
 * @author EX-ZHENGDUANCHUAN001
 * 
 */
public class TableView extends LinearLayout {
	private String TAG = TableView.class.getSimpleName();
	/**
	 * listView
	 */
	private PullListView mListView;
	/**
	 * tableAdapter
	 */
	private TableAdapter mTableAdapter;
	/**
	 * 表头
	 */
	private LinearLayout headerLayout;
	/**
	 * 表尾
	 */
	private LinearLayout footerLayout;
	/**
	 * 随ListView滚动的表头
	 */
	private ArrayList<View> mHeaderView;
	/**
	 * mWindowManager
	 */
	private WindowManager mWindowManager;
	/**
	 * 观察者
	 */
	private AdapterDataSetObserver mDataSetObserver;

	/**
	 * 是否添加默认底部
	 */
	private boolean mIsShowFooter = true;

	/**
	 * ListView填充屏幕的高度
	 */
	private int mFillHeight;

	/**
	 */
	private int mfinalFillHeight;

	private boolean isSetListViewHeight;

	private int tableViewOldX;
	private int tableViewOldY;

	/**
	 * 构造方法
	 * 
	 * @param context
	 *            上下文
	 * @param attrs
	 *            属性
	 */
	public TableView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	/**
	 * 构造方法
	 * 
	 * @param context
	 *            上下文
	 */
	public TableView(Context context) {
		super(context);
		init(context);
	}

	/**
	 * 初始化
	 * 
	 * @param context
	 *            上下文
	 */
	private void init(Context context) {
		this.setOrientation(LinearLayout.VERTICAL);

		LayoutInflater.from(getContext()).inflate(
				R.layout.app_widget_tableview_header_layout, this);
		LayoutInflater.from(getContext()).inflate(
				R.layout.app_widget_tableview, this);
		mListView = (PullListView) findViewById(R.id.listView1);
		headerLayout = (LinearLayout) findViewById(R.id.headerLayout);
		footerLayout = new LinearLayout(context);
		AbsListView.LayoutParams lParams = new AbsListView.LayoutParams(
				AbsListView.LayoutParams.FILL_PARENT,
				AbsListView.LayoutParams.WRAP_CONTENT);
		lParams.height = AbsListView.LayoutParams.WRAP_CONTENT;
		lParams.width = AbsListView.LayoutParams.FILL_PARENT;
		footerLayout.setLayoutParams(lParams);
		footerLayout.setOrientation(LinearLayout.VERTICAL);
		mListView.addFooterView(footerLayout);
		mWindowManager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		mHeaderView = new ArrayList<View>();
		// 监听VIEW的layout事件
		this.getViewTreeObserver().addOnGlobalLayoutListener(
				new OnGlobalLayoutListener() {

					@Override
					public void onGlobalLayout() {
						int[] location = new int[2];
						TableView.this.getLocationOnScreen(location);
						int newX = location[0];
						int newY = location[1];
						APPLog.d(TAG, "ListView 高度计算" + TableView.this
								+ "newX:" + newX + " newY:" + newY);
						if (newX != tableViewOldX
								|| (newY != tableViewOldY && newY > 0)
								|| isSetListViewHeight) {
							setListViewHeightBasedOnChildren(mListView);
						} else if (mfinalFillHeight == 0 && newY > 0) {
							APPLog.d(TAG,
									"ListView 高度计算 保存满屏高度mfinalFillHeight："
											+ mFillHeight);
							mfinalFillHeight = mFillHeight;
						}
						tableViewOldX = newX;
						tableViewOldY = newY;
					}
				});
	}

	/**
	 * 设置适配器
	 * 
	 * @param adapter
	 *            适配器
	 */
	public void setAdapter(TableAdapter adapter) {
		if (adapter == null) {
			return;
		}
		mTableAdapter = adapter;
		if (null != mListView.getAdapter()) {
			mListView.getAdapter().unregisterDataSetObserver(mDataSetObserver);
		}
		// 添加表头
		addHeaderView(adapter);

		// 添加表尾
		addFooterView(adapter);

		mListView.init();
		mListView.setAdapter(adapter);
		mListView.setOnScrollListener(adapter);
		mDataSetObserver = new AdapterDataSetObserver();
		mListView.getAdapter().registerDataSetObserver(mDataSetObserver);
		isSetListViewHeight = true;
		// setListViewHeightBasedOnChildren(mListView);
	}

	/**
	 * 获取随listView滚动的头部高度
	 * 
	 * @return 高度
	 */
	private int getHeaderViewHeight() {
		int totalHeight = 0;
		for (View view : mHeaderView) {
			view.measure(0, 0);
			totalHeight += view.getMeasuredHeight();
		}
		APPLog.d(TAG, "随listView滚动的头部高度:" + totalHeight);
		return totalHeight;
	}

	/**
	 * 获取导航条高度
	 * @param context context
	 * @return 导航条
	 */
	private int getNavigateHeight(Activity context) {
		int height = 0;
		Activity parent = context.getParent();
		while (parent != null) {
//			if (parent instanceof NavigateTabActivity) {
//				height = Tools.getActualSize(context, 83);
//				break;
//			}
//			if (parent instanceof MainActivity) {
//				height = Tools.getActualSize(context, 80);
//				break;
//			}

			parent = parent.getParent();
		}

		return height;
	}

	/**
	 * 计算LISTVIEW高度
	 * 
	 * @param listView
	 *            listView
	 */
	private void setListViewHeightBasedOnChildren(ListView listView) {
		APPLog.d(TAG, "计算LISTVIEW高度 -mTableAdapter:" + mTableAdapter);
		if (mTableAdapter == null) {
			return;
		}
		// 如果满屏高度已被赋值，则不在计算满屏高度
		if (mfinalFillHeight == 0) {
			int navigate = getNavigateHeight((Activity)listView.getContext());
			APPLog.d(TAG, "计算LISTVIEW高度 -导航条高度" + navigate);
			int heightPixels = mWindowManager.getDefaultDisplay().getHeight();
			APPLog.d(TAG, "计算LISTVIEW高度 -屏幕高度:" + heightPixels);
			int[] location = new int[2];
			this.getLocationOnScreen(location);
			int locationY = location[1];
			APPLog.d(TAG, "计算LISTVIEW高度 -TableView 顶部距离屏幕顶部距离:" + locationY);
			headerLayout.measure(0, 0);
			mFillHeight = heightPixels - locationY
					- headerLayout.getMeasuredHeight() - navigate;
			APPLog.d(TAG,
					"计算LISTVIEW高度 - 头部高度:" + headerLayout.getMeasuredHeight());
		}
		APPLog.d(TAG, "计算LISTVIEW高度 - 填充满屏的高度:" + mFillHeight);
		TableAdapter listAdapter = mTableAdapter;

		int count = listAdapter.getCount();
		APPLog.d(TAG, "计算LISTVIEW高度 - count:" + count);
		int totalHeight = 0;
		for (int i = 0; i < count; i++) {
			View listItem = listAdapter.getCleanView(i);
			listItem.measure(0, 0);
			int height = listItem.getMeasuredHeight();
			APPLog.d(TAG, "计算LISTVIEW高度 - itemHeight:" + height);
			totalHeight += height;
			if (totalHeight > mFillHeight) {
				break;
			}
		}
		footerLayout.measure(0, 0);
		int footerHeight = footerLayout.getMeasuredHeight();
		APPLog.d(TAG, "计算LISTVIEW高度 - 底部高度:" + footerHeight);

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		int listHeight = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount()))
				+ footerHeight + getHeaderViewHeight();
		APPLog.d(TAG, "计算LISTVIEW高度 -实际 高度:" + listHeight);
		if (listHeight > mFillHeight) {
			params.height = mFillHeight;
		} else {
			params.height = listHeight;
		}
		listView.setLayoutParams(params);
		isSetListViewHeight = false;
	}

	/**
	 * 数据改变观察者
	 * 
	 * @author EX-ZHENGDUANCHUAN001
	 * 
	 */
	private class AdapterDataSetObserver extends DataSetObserver {

		@Override
		public void onChanged() {
			// setListViewHeightBasedOnChildren(mListView);
			isSetListViewHeight = true;
			APPLog.d(TAG, "数据改变观察者 -onChanged()");
		}

		@Override
		public void onInvalidated() {
			APPLog.d(TAG, "数据改变观察者 -onInvalidated()");
		}
	}

	/**
	 * 添加表头
	 * 
	 * @param adapter
	 *            适配器
	 */
	private void addHeaderView(TableAdapter adapter) {
		// 删除表头view
		headerLayout.removeAllViews();
		View headerView = adapter.getHeaderView();
		if (headerView != null) {
			headerLayout.addView(headerView);
		}
	}

	/**
	 * 添加表尾
	 * 
	 * @param adapter
	 *            适配器
	 */
	private void addFooterView(TableAdapter adapter) {
		footerLayout.removeAllViews();
		View footerView = adapter.getFooterView();
		if (footerView != null) {
			footerView.setOnClickListener(null);
			footerLayout.addView(footerView);
		}
		if (mIsShowFooter) {
			LayoutInflater inflater = LayoutInflater.from(getContext());
			View bottomfooterView = inflater.inflate(
					R.layout.app_widget_table_adapter_footer_bottom, null);
			bottomfooterView.setOnClickListener(null);
			footerLayout.addView(bottomfooterView);
		}
	}

	/**
	 * list项单击事件
	 * 
	 * @param listener
	 *            监听对象
	 */
	public void setOnItemClickListener(OnItemClickListener listener) {
		mListView.setOnItemClickListener(listener);
	}

	/**
	 * list项单击事件
	 * 
	 * @param listener
	 *            监听对象
	 */
	public void setOnTouchListener(OnTouchListener listener) {
		mListView.setOnTouchListener(listener);
	}

	/**
	 * FocusChange
	 * 
	 * @param listener
	 *            监听对象
	 */
	public void setOnFocusChangeListener(OnFocusChangeListener listener) {
		mListView.setOnFocusChangeListener(listener);
	}

	/**
	 * Refresh
	 * 
	 * @param listener
	 *            监听对象
	 */
	public void setOnRefreshListener(OnRefreshListener listener) {
		mListView.setOnRefreshListener(listener);
	}

	/**
	 * refresh
	 */
	public void refresh() {
		mListView.refresh();
	}

	/**
	 * 设置是否支持上推加载
	 * 
	 * @param isSupport
	 *            是否支持
	 */
	public void setSupportPullMode(boolean isSupport) {
		mListView.setSupportPullMode(isSupport);
	}

	/**
	 * 是否添加默认底部
	 * 
	 * @param isShow
	 *            isShow
	 */
	public void showfooter(boolean isShow) {
		mIsShowFooter = isShow;
	}

	/**
	 * 添加随listView滚动的头部
	 * 
	 * @param v
	 *            v
	 */
	public void addHeaderView(View v) {
		mHeaderView.add(v);
		mListView.addHeaderView(v);
	}

	/**
	 * 是否正在加载
	 * @return 是否加载
	 */
	public boolean isRefreshing() {
		return mListView.isRefreshing();
	}
}
